#!/usr/bin/env python

import web
import os
import config
from log import log

'''
Basic controller
'''
class action(object):
    def __init__(self, name=config.NAME):
        self.tmplDir = None
        self.render = None
        self.name = name
        self.globalsTmplFuncs = {
            'makeUrl': self.makeUrl,
            'subStr' :lambda strings,offset,length : self.subText(strings,offset,length)
        }

        self.privData = {
            'TITLE': '%s - %s' % (config.NAME, self.name),
            'NAME': self.name,
            'SITE_URL':  config.URL,
        }

        self.database = os.path.join(config.DATA_DIR, config.DB_NAME)

    def display(self, tmpl):
        if not self.render:
            return None

        return getattr(self.render, tmpl)(self.privData)

    def subText(self,strings,offset,length):
        return self.strip_tags(strings)[offset:length]

    def strip_tags(self,html):
        from HTMLParser import HTMLParser
        html=html.strip()
        html=html.strip("\n")
        result=[]
        parse=HTMLParser()
        parse.handle_data=result.append
        parse.feed(html)
        parse.close()
        return "".join(result)

    def success(self, msg, url='/', timeout=5):
        self.privData['JUMP_MSG'] = msg
        self.privData['JUMP_TIMEOUT'] = timeout
        self.privData['JUMP_URL'] = url

        self.name = 'Success'
        self.privData['TITLE'] = '%s - %s' % (config.NAME, self.name)
        self.privData['NAME'] = self.name

        return self.display('success')
       

    def error(self, msg, url='/', timeout=5):
        self.privData['JUMP_MSG'] = msg
        self.privData['JUMP_TIMEOUT'] = timeout
        self.privData['JUMP_URL'] = url

        self.name = 'Error'
        self.privData['TITLE'] = '%s - %s' % (config.NAME, self.name)
        self.privData['NAME'] = self.name

        return self.display('error')

    def makeUrl(self, url, params={}):
        import urllib
        paramsStr = '?'+ urllib.urlencode(params) if len(params)>0 else ''
        return url + paramsStr

    def notFound(self):
        return self.error(msg='Page not found!')

    def isInstalled(self):
        if os.path.exists(self.database):
            return True

        return False

    def isLogin(self):
        return hasattr(web.ctx.session, 'login') and web.ctx.session.login == True

    def setLogin(self,userData=None):
        if userData == None:
            web.ctx.session.login = False
        else:
            web.ctx.session.login = True
            web.ctx.session.username = userData['username']

    def validates(self,validList):
        userInput=self.getInput()
        for i in validList:
            if not i.validate(userInput[i.name]):
                self.errorMessage=i.note
                return False
        return True

    def getInput(self):
        #return web.input()
        return self.htmlquote(dict(web.input()))

    def htmlquote(self,inputData):
        if isinstance(inputData,dict) == False:
            return web.net.htmlquote(inputData)
        else:
            for k,v in inputData.items():
                inputData[k]= self.htmlquote(v)
        return inputData

    def htmlunquote(self,inputData):
        if isinstance(inputData,dict) == False:
            return web.net.htmlunquote(inputData)
        else:
            for k,v in inputData.items():
                inputData[k]= self.htmlunquote(v)
        return inputData


    def findModule(group, name):
        if not MODULES.has_key(group.lower()):
            return None

        for item in MODULES[group.lower()]:
            if item['name.default'].lower() == name.lower():
                return item

        return None


class modules(object):
    def __init__(self, group):
        self.modules = []

        if not config.MODULES.has_key(group):
            return

        for v in config.MODULES[group]:
            if not v['disabled']:
                self.modules.append((v['id'],[v['name.default'], v['ref']]))
        self.modules.sort(lambda a,b :cmp(a[0], b[0]))

    def get(self):
        return self.modules
        
    def findNeighbors(self, name):
        pass

    def getIdByName(self, name):
        pass
